package com.xbongbong.saas.help;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasFormRefEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.BIProductReformEnum;
import com.xbongbong.paas.enums.BISubProductCompareFieldEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.help.subform.TransferSubFormHelper;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.contractperformance.pojo.ContractPerformanceDataPojo;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.statistic.constant.RelatedProductConstant;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.domain.entity.AssembleProductEntity;
import com.xbongbong.saas.domain.entity.BomProductEntity;
import com.xbongbong.saas.domain.entity.ContractPerformanceEntity;
import com.xbongbong.saas.domain.entity.ContractProductEntity;
import com.xbongbong.saas.domain.entity.InstockProductEntity;
import com.xbongbong.saas.domain.entity.InventoryProductEntity;
import com.xbongbong.saas.domain.entity.OpportunityProductEntity;
import com.xbongbong.saas.domain.entity.OutstockProductEntity;
import com.xbongbong.saas.domain.entity.ProductionOrderProductEntity;
import com.xbongbong.saas.domain.entity.PurchaseProductEntity;
import com.xbongbong.saas.domain.entity.QuotationProductEntity;
import com.xbongbong.saas.domain.entity.ReturnedPurchaseProductEntity;
import com.xbongbong.saas.domain.entity.SupplierProductEntity;
import com.xbongbong.saas.domain.entity.TransferProductEntity;
import com.xbongbong.saas.domain.entity.WarehouseOristockEntity;
import com.xbongbong.saas.enums.ContractProductTypeEnum;
import com.xbongbong.saas.enums.InstockTypeEnum;
import com.xbongbong.saas.enums.OutstockTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.product.ContractProductEnum;
import com.xbongbong.saas.model.AssembleModel;
import com.xbongbong.saas.model.AssembleProductModel;
import com.xbongbong.saas.model.BomBillModel;
import com.xbongbong.saas.model.BomProductModel;
import com.xbongbong.saas.model.ClueModel;
import com.xbongbong.saas.model.CommunicatePlanModel;
import com.xbongbong.saas.model.CompetitorModel;
import com.xbongbong.saas.model.ContactModel;
import com.xbongbong.saas.model.ContractModel;
import com.xbongbong.saas.model.ContractPerformanceModel;
import com.xbongbong.saas.model.ContractProductModel;
import com.xbongbong.saas.model.CreditCardBillModel;
import com.xbongbong.saas.model.CreditFixedLimitModel;
import com.xbongbong.saas.model.CreditLimitModel;
import com.xbongbong.saas.model.CreditTemporaryLimitModel;
import com.xbongbong.saas.model.CustomerCommunicateModel;
import com.xbongbong.saas.model.CustomerModel;
import com.xbongbong.saas.model.CustomerStatementModel;
import com.xbongbong.saas.model.CustomerStatementSnapshotModel;
import com.xbongbong.saas.model.CustomerStatementStatisticsModel;
import com.xbongbong.saas.model.DistributorAccountModel;
import com.xbongbong.saas.model.ExpenseModel;
import com.xbongbong.saas.model.FundTransferModel;
import com.xbongbong.saas.model.InstockModel;
import com.xbongbong.saas.model.InstockProductModel;
import com.xbongbong.saas.model.InventoryModel;
import com.xbongbong.saas.model.InventoryProductModel;
import com.xbongbong.saas.model.InvoiceModel;
import com.xbongbong.saas.model.MarketActivityModel;
import com.xbongbong.saas.model.OnlinePaymentFlowModel;
import com.xbongbong.saas.model.OpportunityModel;
import com.xbongbong.saas.model.OpportunityProductModel;
import com.xbongbong.saas.model.OtherExpenseModel;
import com.xbongbong.saas.model.OtherIncomeModel;
import com.xbongbong.saas.model.OutstockModel;
import com.xbongbong.saas.model.OutstockProductModel;
import com.xbongbong.saas.model.PaasFormDataModel;
import com.xbongbong.saas.model.PayPlanModel;
import com.xbongbong.saas.model.PayPlanSheetModel;
import com.xbongbong.saas.model.PaymentModel;
import com.xbongbong.saas.model.PaymentSheetModel;
import com.xbongbong.saas.model.PaymentTaskModel;
import com.xbongbong.saas.model.ProductModel;
import com.xbongbong.saas.model.ProductionOrderModel;
import com.xbongbong.saas.model.ProductionOrderProductModel;
import com.xbongbong.saas.model.PurchaseInvoiceModel;
import com.xbongbong.saas.model.PurchaseModel;
import com.xbongbong.saas.model.PurchaseProductModel;
import com.xbongbong.saas.model.QuotationModel;
import com.xbongbong.saas.model.QuotationProductModel;
import com.xbongbong.saas.model.RefundModel;
import com.xbongbong.saas.model.ReimbursementFormModel;
import com.xbongbong.saas.model.ReturnedPurchaseModel;
import com.xbongbong.saas.model.ReturnedPurchaseProductModel;
import com.xbongbong.saas.model.SupplierCommunicateModel;
import com.xbongbong.saas.model.SupplierContactModel;
import com.xbongbong.saas.model.SupplierModel;
import com.xbongbong.saas.model.SupplierProductModel;
import com.xbongbong.saas.model.TransferModel;
import com.xbongbong.saas.model.TransferProductModel;
import com.xbongbong.saas.model.WarehouseModel;
import com.xbongbong.saas.model.WarehouseOristockModel;
import com.xbongbong.saas.model.WorkOrderModel;
import com.xbongbong.saas.model.WorkReportModel;
import com.xbongbong.saas.model.CostAdjustModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author 梁鲁江
 * @version v1.0
 * @date 2019/3/15 9:04
 * @since v1.0
 */
@Component
public class InitDataHelp {
    @Resource
    private PaasFormDataModel paasFormDataModel;
    @Resource
    private CustomerModel customerModel;
    @Resource
    private ContactModel contactModel;
    @Resource
    private ProductModel productModel;
    @Resource
    private OpportunityModel opportunityModel;
    @Resource
    private InventoryModel inventoryModel;
    @Resource
    private TransferModel transferModel;
    @Resource
    private WarehouseModel warehouseModel;
    @Resource
    private ContractModel contractModel;
    @Resource
    private RefundModel refundModel;
    @Resource
    private CommunicatePlanModel communicatePlanModel;
    @Resource
    private WorkReportModel workReportModel;
    @Resource
    private CustomerCommunicateModel customerCommunicateModel;
    @Resource
    private SupplierCommunicateModel supplierCommunicateModel;
    @Resource
    private BomBillModel bomBillModel;
    @Resource
    private ProductionOrderModel productionOrderModel;
    @Resource
    private PaymentModel paymentModel;
    @Resource
    private PayPlanModel payPlanModel;
    @Resource
    private InvoiceModel invoiceModel;
    @Resource
    private PaymentSheetModel paymentSheetModel;
    @Resource
    private WorkOrderModel workOrderModel;
    @Resource
    private SupplierModel supplierModel;
    @Resource
    private SupplierContactModel supplierContactModel;
    @Resource
    private PurchaseModel purchaseModel;
    @Resource
    private InstockModel instockModel;
    @Resource
    private OutstockModel outstockModel;
    @Resource
    private AssembleModel assembleModel;
    @Resource
    private ReturnedPurchaseModel returnedPurchaseModel;
    @Resource
    private ContractProductModel contractProductModel;
    @Resource
    private InstockProductModel instockProductModel;
    @Resource
    private OpportunityProductModel opportunityProductModel;
    @Resource
    private OutstockProductModel outstockProductModel;
    @Resource
    private ProductionOrderProductModel productionOrderProductModel;
    @Resource
    private PurchaseProductModel purchaseProductModel;
    @Resource
    private ReturnedPurchaseProductModel returnedPurchaseProductModel;
    @Resource
    private SupplierProductModel supplierProductModel;
    @Resource
    private ContractPerformanceModel contractPerformanceModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private PayPlanSheetModel payPlanSheetModel;
    @Resource
    private QuotationModel quotationModel;
    @Resource
    private PurchaseInvoiceModel purchaseInvoiceModel;
    @Resource
    private TransferSubFormHelper transferSubFormHelper;
    @Resource
    private ReimbursementFormModel reimbursementFormModel;
    @Resource
    private ExpenseModel expenseModel;
    @Resource
    private MarketActivityModel marketActivityModel;
    @Resource
    private ClueModel clueModel;
    @Resource
    private WarehouseOristockModel warehouseOristockModel;
    @Resource
    private PaymentTaskModel paymentTaskModel;
    @Resource
    private OnlinePaymentFlowModel onlinePaymentFlowModel;
    @Resource
    private CustomerStatementModel customerStatementModel;
    @Resource
    private CustomerStatementStatisticsModel customerStatementStatisticsModel;
    @Resource
    private CustomerStatementSnapshotModel customerStatementSnapshotModel;
    @Resource
    private CreditLimitModel creditLimitModel;
    @Resource
    private CreditTemporaryLimitModel creditTemporaryLimitModel;
    @Resource
    private CreditFixedLimitModel creditFixedLimitModel;
    @Resource
    private CreditCardBillModel creditCardBillModel;
    @Resource
    private OtherIncomeModel otherIncomeModel;
    @Resource
    private OtherExpenseModel otherExpenseModel;
    @Resource
    private FundTransferModel fundTransferModel;
    @Resource
    private DistributorAccountModel distributorAccountModel;
    @Resource
    private AssembleProductModel assembleProductModel;
    @Resource
    private InventoryProductModel inventoryProductModel;
    @Resource
    private TransferProductModel transferProductModel;
    @Resource
    private QuotationProductModel quotationProductModel;
    @Resource
    private BomProductModel bomProductModel;
    @Resource
    private CompetitorModel competitorModel;
    @Resource
    private CostAdjustModel costAdjustModel;

    private static final Logger LOG = LoggerFactory.getLogger(InitDataHelp.class);

    public List getList(Integer businessType, Integer saasMark, Map<String, Object> params, Integer fromInit, PaasFormRefEntity paasFormRefEntity) throws XbbException {
        List list = new ArrayList();
        if (SaasMarkEnum.PAAS.getCode().equals(saasMark)) {
            list = paasFormDataModel.findEntityOriginal(params);
        } else {
            if (businessType == null || businessType.equals(0)) {
                LOG.error("businessType为空");
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
            switch (xbbRefTypeEnum) {
                case CUSTOMER_MANAGEMENT:
                    list = customerModel.findEntitysWithoutSub(params);
                    break;
                case CONTRACT:
                    list = contractModel.findEntitysWithoutSub(params);
                    break;
                case CONTACT:
                    list = contactModel.findEntitysWithoutSub(params);
                    break;
                case PRODUCT:
                    if (!Objects.equals(fromInit,1)) {
                        params.put("dataParentIdGte", 0L);
                    }
                    list = productModel.findEntitysByPaas(params);
                    break;
                case SALES_OPPORTUNITY:
                    list = opportunityModel.findEntitysWithoutSub(params);
                    break;
                case INVENTORY:
                    list = inventoryModel.findEntitysWithoutSub(params);
                    break;
                case TRANSFER:
                    list = transferModel.findEntitysWithoutSub(params);
                    break;
                case WAREHOUSE:
                    list = warehouseModel.findEntitysWithoutSub(params);
                    break;
                case COMMUNICATE_PLAN:
                    list = communicatePlanModel.findEntitysWithoutSub(params);
                    break;
                case WORK_REPORT:
                    list = workReportModel.findEntitysWithoutSub(params);
                    break;
                case CUSTOMER_COMMUNICATE:
                    //只要AUTO_GEN("num_2")=0 的数据（非自动生成）
                    if (!Objects.equals(fromInit,1)) {
                        list = customerCommunicateModel.findNotAutGenEntitysWithoutSub(params);
                    }else {
                        list = customerCommunicateModel.findEntitysWithoutSub(params);
                    }
                    break;
                case SUPPLIER_COMMUNICATE:
                    list = supplierCommunicateModel.findEntitysWithoutSub(params);
                    break;
                case BOM_BILL:
                    list = bomBillModel.findEntitysWithoutSub(params);
                    break;
                case PRODUCTION_ORDER:
                    list = productionOrderModel.findEntitysWithoutSub(params);
                    break;
                case PAYMENT:
                    list = paymentModel.findEntitysWithoutSub(params);
                    break;
                case PAYMENT_SHEET:
                    list = paymentSheetModel.findEntitysWithoutSub(params);
                    break;
                case PAY_PLAN:
                    list = payPlanModel.findEntitysWithoutSub(params);
                    break;
                case PAY_SHEET:
                    list = payPlanSheetModel.findEntitysWithoutSub(params);
                    break;
                case INVOICE:
                    list = invoiceModel.findEntitysWithoutSub(params);
                    break;
                case PURCHASE_INVOICE:
                    list = purchaseInvoiceModel.findEntitysWithoutSub(params);
                    break;
                case OTHER_INCOME:
                    list = otherIncomeModel.findEntitysWithoutSub(params);
                    break;
                case OTHER_EXPENSE:
                    list = otherExpenseModel.findEntitysWithoutSub(params);
                    break;
                case FUND_TRANSFER:
                    list = fundTransferModel.findEntitysWithoutSub(params);
                    break;
                case WORK_ORDER:
                    list = workOrderModel.findEntitysWithoutSub(params);
                    break;
                case SUPPLIER:
                    list = supplierModel.findEntitysWithoutSub(params);
                    break;
                case SUPPLIER_CONTACT:
                    list = supplierContactModel.findEntitysWithoutSub(params);
                    break;
                case PURCHASE:
                    list = purchaseModel.findEntitysWithoutSub(params);
                    break;
                case RETURNED_PURCHASE:
                    list = returnedPurchaseModel.findEntitysWithoutSub(params);
                    break;
                case INSTOCK:
                case PURCHASE_INSTOCK:
                case REFUND_INSTOCK:
                case OTHER_INSTOCK:
                case PRODUCTION_INSTOCK:
                case RETURNED_MATERIEL_INSTOCK:
                    list = instockModel.findEntitysWithoutSub(params);
                    break;
                case OUTSTOCK:
                case CONTRACT_OUTSTOCK:
                case PRODUCTION_MATERIEL_OUTSTOCK:
                case OTHER_OUTSTOCK:
                case WORK_ORDER_OUTSTOCK:
                case RETURNED_PURCHASE_OUTSTOCK:
                    list = outstockModel.findEntitysWithoutSub(params);
                    break;
                case ASSEMBLE:
                    list = assembleModel.findEntitysWithoutSub(params);
                    break;
                case REFUND:
                    list = refundModel.findEntitysWithoutSub(params);
                    break;
                case CONTRACT_PRODUCT:
                    if (Objects.nonNull(paasFormRefEntity)) {
                        params.put("type", paasFormRefEntity.getType());
                        //代表是BI多表关联那边的逻辑
                        if (Objects.nonNull(paasFormRefEntity.getType()) && Objects.equals(paasFormRefEntity.getType(), ContractProductTypeEnum.REFUND.getCode())) {
                            //因为退货退款不存formId
                            params.remove("formId");
                        }
                        List<ContractProductEntity>  contractProductList = contractProductModel.findEntitys(params);
                        list = transferSubProduct(contractProductList, paasFormRefEntity);
                    }else {
                        params.put("type", ContractProductTypeEnum.CONTNRACT.getCode());
                        List<ContractProductEntity>  contractProductList = contractProductModel.findEntitys(params);
                        list = transferSubFormHelper.transferContractProductToFormDataList(contractProductList);
                    }
                    break;
                case SALES_OPPORTUNITY_PRODUCT:
                    //现在这边虽然es的init方法也会调用到，但是这个子表单不入es，所以这边我默认是BI多表关联那边的逻辑
                    List<OpportunityProductEntity> opportunityProductEntityList = opportunityProductModel.findEntitys(params);
                    if(CollectionsUtil.isEmpty(opportunityProductEntityList)){
                        break;
                    }
                    list = transferSubProduct(opportunityProductEntityList, paasFormRefEntity);
                    break;
                case QUOTATION_PRODUCT :
                    //现在这边虽然es的init方法也会调用到，但是这个子表单不入es，所以这边我默认是BI多表关联那边的逻辑
                    List<QuotationProductEntity> quotationProductEntities = quotationProductModel.findEntitys(params);
                    if(CollectionsUtil.isEmpty(quotationProductEntities)){
                        break;
                    }
                    list = transferSubProduct(quotationProductEntities, paasFormRefEntity);
                    break;
                case SUPPLIER_PRODUCT:
                    //现在这边虽然es的init方法也会调用到，但是这个子表单不入es，所以这边我默认是BI多表关联那边的逻辑
                    List<SupplierProductEntity> supplierProductEntityList = supplierProductModel.findEntitys(params);
                    if(CollectionsUtil.isEmpty(supplierProductEntityList)){
                        break;
                    }
                    list = transferSubProduct(supplierProductEntityList, paasFormRefEntity);
                    break;
                case PURCHASE_PRODUCT:
                    //现在这边虽然es的init方法也会调用到，但是这个子表单不入es，所以这边我默认是BI多表关联那边的逻辑
                    List<PurchaseProductEntity> purchaseProductEntityList = purchaseProductModel.findEntitys(params);
                    if(CollectionsUtil.isEmpty(purchaseProductEntityList)){
                        break;
                    }
                    list = transferSubProduct(purchaseProductEntityList, paasFormRefEntity);
                    break;
                case RETURNEDPURCHASE_PRODUCT:
                    //现在这边虽然es的init方法也会调用到，但是这个子表单不入es，所以这边我默认是BI多表关联那边的逻辑
                    List<ReturnedPurchaseProductEntity> returnedPurchaseProductEntityList = returnedPurchaseProductModel.findEntitys(params);
                    if(CollectionsUtil.isEmpty(returnedPurchaseProductEntityList)){
                        break;
                    }
                    list = transferSubProduct(returnedPurchaseProductEntityList, paasFormRefEntity);
                    break;
                case BOM_BILL_PRODUCT:
                    //现在这边虽然es的init方法也会调用到，但是这个子表单不入es，所以这边我默认是BI多表关联那边的逻辑
                    params.put("type", paasFormRefEntity.getType());
                    List<BomProductEntity> bomProductEntities = bomProductModel.findEntitys(params);
                    if (CollectionsUtil.isEmpty(bomProductEntities)) {
                        break;
                    }
                    list = transferSubProduct(bomProductEntities, paasFormRefEntity);
                    break;
                case PRODUCTION_ORDER_PRODUCT:
                    //现在这边虽然es的init方法也会调用到，但是这个子表单不入es，所以这边我默认是BI多表关联那边的逻辑
                    params.put("type", paasFormRefEntity.getType());
                    List<ProductionOrderProductEntity> productionOrderProductEntityList = productionOrderProductModel.findEntitys(params);
                    if(CollectionsUtil.isEmpty(productionOrderProductEntityList)){
                        break;
                    }
                    list = transferSubProduct(productionOrderProductEntityList, paasFormRefEntity);
                    break;
                case ASSEMBLE_PRODUCT:
                case ASSEMBLE_INPRODUCTS:
                    //现在这边虽然es的init方法也会调用到，但是这个子表单不入es，所以这边我默认是BI多表关联那边的逻辑
                    params.put("type", paasFormRefEntity.getType());
                    List<AssembleProductEntity> assembleProductEntities = assembleProductModel.findEntitys(params);
                    if(CollectionsUtil.isEmpty(assembleProductEntities)){
                        break;
                    }
                    list = transferSubProduct(assembleProductEntities, paasFormRefEntity);
                    break;
                case INVENTORY_PRODUCT:
                    //现在这边虽然es的init方法也会调用到，但是这个子表单不入es，所以这边我默认是BI多表关联那边的逻辑
                    List<InventoryProductEntity> inventoryProductEntities = inventoryProductModel.findEntitys(params);
                    if(CollectionsUtil.isEmpty(inventoryProductEntities)){
                        break;
                    }
                    list = transferSubProduct(inventoryProductEntities, paasFormRefEntity);
                    break;
                case TRANSFER_PRODUCT:
                    //现在这边虽然es的init方法也会调用到，但是这个子表单不入es，所以这边我默认是BI多表关联那边的逻辑
                    List<TransferProductEntity> transferProductEntities = transferProductModel.findEntitys(params);
                    if(CollectionsUtil.isEmpty(transferProductEntities)){
                        break;
                    }
                    list = transferSubProduct(transferProductEntities, paasFormRefEntity);
                    break;
                case INSTOCK_PRODUCT:
                    Integer instockProductType = paasFormRefEntity.getType();
                    //现在这边虽然es的init方法也会调用到，但是这个子表单不入es，所以这边我默认是BI多表关联那边的逻辑
                    if (Objects.equals(instockProductType, InstockTypeEnum.OTHER_INSTOCK.getCode())) {
                        params.put("types", Arrays.asList(InstockTypeEnum.INVENTORY_INSTOCK.getCode(), InstockTypeEnum.TRANSFER_INSTOCK.getCode(),
                                InstockTypeEnum.OTHER_INSTOCK.getCode(), InstockTypeEnum.ASSEMBLE_INSTOCK.getCode()));
                    }else {
                        params.put("type", instockProductType);
                    }
                    //因为发现有些数据没有formId,所以这边强制把formId移除掉
                    params.remove("formId");
                    List<InstockProductEntity> instockProductEntities = instockProductModel.findEntitys(params);
                    if(CollectionsUtil.isEmpty(instockProductEntities)){
                        break;
                    }
                    list = transferSubProduct(instockProductEntities, paasFormRefEntity);
                    break;
                case OUTSTOCK_PRODUCT:
                    Integer outStockType = paasFormRefEntity.getType();
                    //现在这边虽然es的init方法也会调用到，但是这个子表单不入es，所以这边我默认是BI多表关联那边的逻辑
                    if (Objects.equals(outStockType, OutstockTypeEnum.OTHER_OUTSTOCK.getCode())) {
                        params.put("types", Arrays.asList(OutstockTypeEnum.INVENTORY_OUTSTOCK.getCode(), OutstockTypeEnum.TRANSFER_OUTSTOCK.getCode(),
                                OutstockTypeEnum.OTHER_OUTSTOCK.getCode(), OutstockTypeEnum.ASSEMBLE_OUTSTOCK.getCode()));
                    }else {
                        params.put("type", paasFormRefEntity.getType());
                    }
                    //因为发现有些数据没有formId,所以这边强制把formId移除掉
                    params.remove("formId");
                    List<OutstockProductEntity> outstockProductEntityList = outstockProductModel.findEntitys(params);
                    if(CollectionsUtil.isEmpty(outstockProductEntityList)){
                        break;
                    }
                    list = transferSubProduct(outstockProductEntityList, paasFormRefEntity);
                    break;
                case CONTRACT_PERFORMANCE:
                    List<ContractPerformanceEntity>  contractPerformanceList= contractPerformanceModel.findEntitys(params);
                    if(CollectionsUtil.isEmpty(contractPerformanceList)){
                        break;
                    }
                    PaasFormEntityExt contractPerformanceForm = paasFormModel.getByBusinessType(businessType, contractPerformanceList.get(0).getCorpid());
                    if(contractPerformanceForm == null){
                        break;
                    }
                    //TODO  分配金额
                    for (ContractPerformanceEntity contractPerformanceEntity : contractPerformanceList) {
                        PaasFormDataEntityExt  paasFormDataEntityExt = new PaasFormDataEntityExt();
                        paasFormDataEntityExt.setCorpid(contractPerformanceEntity.getCorpid());
                        paasFormDataEntityExt.setAddTime(contractPerformanceEntity.getAddTime());
                        paasFormDataEntityExt.setUpdateTime(contractPerformanceEntity.getUpdateTime());
                        paasFormDataEntityExt.setDel(contractPerformanceEntity.getDel());
                        paasFormDataEntityExt.setId(contractPerformanceEntity.getId());
                        paasFormDataEntityExt.setDataId(contractPerformanceEntity.getId());
                        //formId
                        paasFormDataEntityExt.setFormId(contractPerformanceForm.getId());
                        //data内
                        ContractPerformanceDataPojo  contractPerformanceDataPojo = new ContractPerformanceDataPojo();
                        contractPerformanceDataPojo.setNum_1(contractPerformanceEntity.getContractId());
                        contractPerformanceDataPojo.setNum_2(contractPerformanceEntity.getIsSign());
                        contractPerformanceDataPojo.setNum_3(contractPerformanceEntity.getRate());
                        contractPerformanceDataPojo.setText_1(contractPerformanceEntity.getUserId());
                        paasFormDataEntityExt.setData(JSON.parseObject(JSON.toJSON(contractPerformanceDataPojo).toString()));
                        list.add(paasFormDataEntityExt);
                    }
                    break;
                case QUOTATION:
                    list = quotationModel.findEntitysWithoutSub(params);
                    break;
                case REIMBURSEMENT_FORM:
                    list = reimbursementFormModel.findEntitys(params);
                    break;
                case EXPENSE:
                    list = expenseModel.findEntitys(params);
                    break;
                case MARKET_ACTIVITY:
                    list = marketActivityModel.findEntitysWithoutSub(params);
                    break;
                case CLUE:
                    list = clueModel.findEntitysWithoutSub(params);
                    break;
                case ORI_STOCK:
                    List<WarehouseOristockEntity> entityList = warehouseOristockModel.findEntitys(params);
                    for (WarehouseOristockEntity warehouseOristockEntity : entityList) {
                        PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
                        BeanUtil.copyProperties(warehouseOristockEntity, paasFormDataEntity);
                        paasFormDataEntity.setId(Long.parseLong(warehouseOristockEntity.getId().toString()));
                        JSONObject jsonObject = new JSONObject();
                        paasFormDataEntity.setData(jsonObject);
                        paasFormDataEntity.setDel(Integer.parseInt(warehouseOristockEntity.getDel().toString()));
                        list.add(paasFormDataEntity);
                    }
                    break;
                case CUSTOMER_STATEMENT:
                    list = customerStatementModel.findEntitys(params);
                    break;
                case CUSTOMER_STATEMENT_STATISTIC:
                    list = customerStatementStatisticsModel.findEntitys(params);
                    break;
                case CUSTOMER_STATEMENT_SNAPSHOT:
                    list = customerStatementSnapshotModel.findEntitys(params);
                    break;
                case PAYMENT_TASK:
                    list = paymentTaskModel.findEntitysWithoutSub(params);
                    break;
                case ONLINE_PAYMENT_FLOW:
                    list = onlinePaymentFlowModel.findEntities(params);
                    break;
                case CREDIT_LIMIT:
                    list = creditLimitModel.findEntities(params);
                    break;
                case CREDIT_TEMPORARY_LIMIT:
                    list = creditTemporaryLimitModel.findEntitys(params);
                    break;
                case CREDIT_FIXED_LIMIT:
                    list = creditFixedLimitModel.findEntitys(params);
                    break;
                case CREDIT_CARD_BILL:
                    list = creditCardBillModel.findEntities(params);
                    break;
                case DISTRIBUTOR_ACCOUNT:
                    list = distributorAccountModel.findEntitys(params);
                    break;
                case COMPETITOR:
                    list = competitorModel.findEntitysWithoutSub(params);
                    break;
                case COST_ADJUST:
                    list = costAdjustModel.findEntitys(params);
                    break;
                default:
                    break;
            }
        }
        return list;
    }


    /**
     * 把所有返回的产品子表单信息进行处理一下，返回成PaasFormDataEntityExt，以便兼容成普通列表的处理
     *
     * @param subProductList  子产品表单列表
     * @param paasFormRefEntity  表单关联表信息，目前主要用于多表关联时选择表信息
     * @return
     */
    public <T> List<PaasFormDataEntityExt> transferSubProduct(List<T> subProductList, PaasFormRefEntity paasFormRefEntity) throws XbbException {
        if (Objects.isNull(paasFormRefEntity)) {
            return new ArrayList();
        }
        Integer type = paasFormRefEntity.getType();
        Integer businessType = paasFormRefEntity.getBusinessType();
        BIProductReformEnum biProductReformEnum = BIProductReformEnum.getBiProductReformByType(businessType, type);
        if (Objects.isNull(biProductReformEnum)) {
            return new ArrayList();
        }
        //产品子表单关联主业务的id
        String dbFieldLinkMainBusiness = biProductReformEnum.getDbFieldLinkMainBusiness();
        String virtualLinkMainBusinessAttr = biProductReformEnum.getVirtualLinkMainBusinessAttr();
        //产品子表单产品编号
        String linkProductNoAttr = RelatedProductConstant.COMMON_PRODUCT_SERIAL_NO_ATTR;
        //产品子表单产品名称
        String linkProductNameAttr = biProductReformEnum.getSubLinkProductAttr();
        //产品子表单关联关联子业务的id
        String virtualLinkProductAttr = biProductReformEnum.getVirtualLinkProductAttr();
        //产品id
        String productIdStr = RelatedProductConstant.PRODUCT_ID;
        List<PaasFormDataEntityExt> returnPaasFormDataEntityList = new ArrayList<>();
        try {
            for (T t : subProductList) {
                Class tClass = t.getClass();
                //产品子表单关联主业务id
                Field mainBusField = tClass.getDeclaredField(dbFieldLinkMainBusiness);
                mainBusField.setAccessible(true);
                Long subProductLinkMainId = (Long)mainBusField.get(t);
                //产品子表单中的产品id
                Field productIdField = tClass.getDeclaredField(productIdStr);
                productIdField.setAccessible(true);
                String subProductId = String.valueOf(productIdField.get(t));
                PaasFormDataEntityExt paasFormDataEntityExt = new PaasFormDataEntityExt();
                BeanUtil.copyProperties(t, paasFormDataEntityExt);
                JSONObject data =  paasFormDataEntityExt.getData();
                if (Objects.isNull(data) || data.size() == BasicConstant.ZERO) {
                    JSONObject newJsonObj = handleFieldMap(t, tClass, data, paasFormRefEntity);
                    paasFormDataEntityExt.setData(newJsonObj);
                }
                JSONObject newJsonObj = paasFormDataEntityExt.getData();
                //处理宽表中存在，但是data中不存在
                handDbFieldExist(t, tClass, newJsonObj, paasFormRefEntity);
                //产品子表单中的关联产品的产品id
                Long productId = newJsonObj.getLong(linkProductNameAttr);
                newJsonObj.put(virtualLinkProductAttr, productId);
                newJsonObj.put(virtualLinkMainBusinessAttr, subProductLinkMainId);
                newJsonObj.put(linkProductNoAttr,subProductId);
                newJsonObj.put(linkProductNameAttr,subProductId);
                //产品子表单的审批状态默认为无需审批
                paasFormDataEntityExt.setFlowStatus(FlowStatusEnum.NOT_NEED_APPROVAL.getType());
                returnPaasFormDataEntityList.add(paasFormDataEntityExt);
            }
        }catch (Exception e) {
            LOG.error("转化子产品有问题：{}", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return returnPaasFormDataEntityList;
    }

    /**
     * 处理数据库宽表存在，但是data里面不存
     *
     * @param newJsonObj
     * @param paasFormRefEntity
     */
    private <T> void handDbFieldExist(T t, Class tClass, JSONObject newJsonObj, PaasFormRefEntity paasFormRefEntity) throws XbbException {
        Integer businessType = paasFormRefEntity.getBusinessType();
        Integer type = paasFormRefEntity.getType();
        Map<String, String> fieldMap = BISubProductCompareFieldEnum.getDbFieldExistHandleMap(businessType, type);
        if (Objects.isNull(fieldMap) || fieldMap.size() == BasicConstant.ZERO) {
            return;
        } else {
            try {
                for (Map.Entry<String, String> entryMap : fieldMap.entrySet()) {
                    String dbKey = entryMap.getKey();
                    String dataKey = entryMap.getValue();
                    if (Objects.isNull(dbKey) || StringUtil.isEmpty(dbKey)) {
                        continue;
                    }else {
                        Field field = tClass.getDeclaredField(dbKey);
                        field.setAccessible(true);
                        Object finalValue = field.get(t);
                        newJsonObj.put(dataKey, finalValue);
                    }
                }
            }catch (Exception e) {
                LOG.error("产品子表单字段解析报错：{}", e);
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
            }
        }
    }

    /**
     * 处理产品子表单宽表跟data里面的字段进行映射
     *
     * @param tClass
     * @param data
     * @param <T>
     */
    private <T> JSONObject handleFieldMap(T t, Class tClass, JSONObject data, PaasFormRefEntity paasFormRefEntity) throws XbbException {
        data = new JSONObject();
        Integer businessType = paasFormRefEntity.getBusinessType();
        Integer type = paasFormRefEntity.getType();
        Map<String, String> fieldMap = BISubProductCompareFieldEnum.getMappingFieldMap(businessType, type);
        List<String> dateTimeAttrList = BISubProductCompareFieldEnum.getDateTimeList(businessType, type);

        BIProductReformEnum biProductReformEnum = BIProductReformEnum.getBiProductReformByType(businessType, type);
        try {
            for (Map.Entry<String, String> entryMap : fieldMap.entrySet()) {
                String key = entryMap.getKey();
                String dbKey = entryMap.getValue();
                if (Objects.isNull(dbKey) || StringUtil.isEmpty(dbKey)) {
                    continue;
                }else {
                    Field field = tClass.getDeclaredField(dbKey);
                    field.setAccessible(true);
                    Object finalValue = field.get(t);
                    if (CollectionsUtil.isNotEmpty(dateTimeAttrList) && dateTimeAttrList.contains(key)) {
                        if (Objects.nonNull(finalValue)) {
                            finalValue = Arith.div((Long)finalValue, 86400D);
                        }
                    }
                    //这边又有特殊逻辑来了，退货退款宽表里面退货数量存的是个负数
                    if (Objects.equals(biProductReformEnum, BIProductReformEnum.REFUND_PRODUCT) && Objects.equals(key, ContractProductEnum.NUM.getAttr())) {
                        data.put(key, -(double)finalValue);
                    }else {
                        data.put(key, finalValue);
                    }
                }
            }
        }catch (Exception e) {
            LOG.info("解析产品子表单老数据报错：{}", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return data;
    }


    /**
     * 根据条件查询数量
     * @param businessType  业务类型
     * @param saasMark   区分saas和paas
     * @param params       参数合集
     * @return
     * @throws XbbException
     */
    public Integer getEntitysCount(Integer businessType, Integer saasMark, Map<String, Object> params) throws XbbException {
        Integer count = 0;
        try{
            if (SaasMarkEnum.PAAS.getCode().equals(saasMark)) {
                count = paasFormDataModel.getEntitysCount(params);
            } else {
                if (businessType == null || businessType.equals(0)) {
                    LOG.error("businessType为空");
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
                }
                XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
                switch (xbbRefTypeEnum) {
                    case CUSTOMER_MANAGEMENT:
                        count = customerModel.getEntitysCount(params);
                        break;
                    case CONTRACT:
                        count = contractModel.getEntitysCount(params);
                        break;
                    case CONTACT:
                        count = contactModel.getEntitysCount(params);
                        break;
                    case PRODUCT:
                        count = productModel.getEntitysCount(params);
                        break;
                    case SALES_OPPORTUNITY:
                        count = opportunityModel.getEntitysCount(params);
                        break;
                    case INVENTORY:
                        count = inventoryModel.getEntitysCount(params);
                        break;
                    case TRANSFER:
                        count = transferModel.getEntitysCount(params);
                        break;
                    case WAREHOUSE:
                        count = warehouseModel.getEntitysCount(params);
                        break;
                    case COMMUNICATE_PLAN:
                        count = communicatePlanModel.getEntitysCount(params);
                        break;
                    case WORK_REPORT:
                        count = workReportModel.getEntitysCount(params);
                        break;
                    case CUSTOMER_COMMUNICATE:
                        count = customerCommunicateModel.getEntitysCount(params);
                        break;
                    case SUPPLIER_COMMUNICATE:
                        count = supplierCommunicateModel.getEntitysCount(params);
                        break;
                    case BOM_BILL:
                        count = bomBillModel.getEntitysCount(params);
                        break;
                    case PRODUCTION_ORDER:
                        count = productionOrderModel.getEntitysCount(params);
                        break;
                    case PAYMENT:
                        count = paymentModel.getEntitysCount(params);
                        break;
                    case PAYMENT_SHEET:
                        count = paymentSheetModel.getEntitysCount(params);
                        break;
                    case PAY_PLAN:
                        count = payPlanModel.getEntitysCount(params);
                        break;
                    case INVOICE:
                        count = invoiceModel.getEntitysCount(params);
                        break;
                    case WORK_ORDER:
                        count = workOrderModel.getEntitysCount(params);
                        break;
                    case SUPPLIER:
                        count = supplierModel.getEntitysCount(params);
                        break;
                    case SUPPLIER_CONTACT:
                        count = supplierContactModel.getEntitysCount(params);
                        break;
                    case PURCHASE:
                        count = purchaseModel.getEntitysCount(params);
                        break;
                    case RETURNED_PURCHASE:
                        count = returnedPurchaseModel.getEntitysCount(params);
                        break;
                    case INSTOCK:
                        count = instockModel.getEntitysCount(params);
                        break;
                    case OUTSTOCK:
                        count = outstockModel.getEntitysCount(params);
                        break;
                    case ASSEMBLE:
                        count = assembleModel.getEntitysCount(params);
                        break;
                    case REFUND:
                        count = refundModel.getEntitysCount(params);
                        break;
                    case CONTRACT_PRODUCT:
                        params.put("type", ContractProductTypeEnum.CONTNRACT.getCode());
                        count = contractProductModel.getEntitysCount(params);
                        break;
                    case INSTOCK_PRODUCT:
                        count = instockProductModel.getEntitysCount(params);
                        break;
                    case SALES_OPPORTUNITY_PRODUCT:
                        count = opportunityProductModel.getEntitysCount(params);
                        break;
                    case OUTSTOCK_PRODUCT:
                        count = outstockProductModel.getEntitysCount(params);
                        break;
                    case PRODUCTION_ORDER_PRODUCT:
                        count = productionOrderProductModel.getEntitysCount(params);
                        break;
                    case PURCHASE_PRODUCT:
                        count = purchaseProductModel.getEntitysCount(params);
                        break;
                    case RETURNEDPURCHASE_PRODUCT:
                        count = returnedPurchaseProductModel.getEntitysCount(params);
                        break;
                    case SUPPLIER_PRODUCT:
                        count = supplierProductModel.getEntitysCount(params);
                        break;
                    case CONTRACT_PERFORMANCE:
                        count = contractPerformanceModel.getEntitysCount(params);
                        break;
                    case QUOTATION:
                        count = quotationModel.getEntitysCount(params);
                        break;
                    case PAY_SHEET:
                        count = payPlanSheetModel.getEntitysCount(params);
                        break;
                    case REIMBURSEMENT_FORM:
                        count = reimbursementFormModel.getEntitysCount(params);
                        break;
                    case EXPENSE:
                        count = expenseModel.getEntitysCount(params);
                        break;
                    case CLUE:
                        count = clueModel.getEntitysCount(params);
                        break;
                    case CUSTOMER_STATEMENT:
                        count = customerStatementModel.getEntitysCount(params);
                        break;
                    case CUSTOMER_STATEMENT_STATISTIC:
                        count = customerStatementStatisticsModel.getEntitysCount(params);
                        break;
                    case CUSTOMER_STATEMENT_SNAPSHOT:
                        count = customerStatementSnapshotModel.getEntitysCount(params);
                        break;
                    case MARKET_ACTIVITY:
                        count = marketActivityModel.getEntitysCount(params);
                        break;
                    case PAYMENT_TASK:
                        count = paymentTaskModel.getEntitysCount(params);
                        break;
                    case ONLINE_PAYMENT_FLOW:
                        count = onlinePaymentFlowModel.getEntitysCount(params);
                        break;
                    case CREDIT_LIMIT:
                        count = creditLimitModel.getEntityCount(params);
                        break;
                    case CREDIT_TEMPORARY_LIMIT:
                        count = creditTemporaryLimitModel.getEntitysCount(params);
                        break;
                    case CREDIT_FIXED_LIMIT:
                        count = creditFixedLimitModel.getEntitysCount(params);
                        break;
                    case CREDIT_CARD_BILL:
                        count = creditCardBillModel.getEntityCount(params);
                        break;
                    default:
                        break;
                }
            }
        }catch (Exception e){
            //防止报错赋默认值
            count = 0;
            LOG.error("getEntitysCount报错：",e);
        }

        return count;
    }
}
